<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/17
 * Time: 13:01
 */

namespace app\admin\controller;

use app\admin\validate\Cannnel;
use app\common\controller\AdminBase;
use think\facade\Db;
use think\facade\View;
use think\facade\Filesystem;

class Channel extends AdminBase
{
    public function index()
    {
        $agency = \app\common\model\Agency::getAgency();
        return View::fetch('index',['agency'=>$agency]);
    }

    //分类管理
    public function channel_json()
    {
        $map = [];
        $aid = input('aid');
        $key = input('key');
        if(!empty($aid)){
            array_push($map,['aid','=',$aid]);
        }

        if(!empty($key)){
            array_push($map,['a.name|a.code','like','%'.$key.'%']);
        }


        $list = Db::name('channel')->alias('a')->join('agency b','a.aid = b.id')->where($map)->order('a.create_time')->field('a.id,a.name,b.name as agency,a.memo,a.code')->paginate(10);

        $this->result($list);
    }

    //分类添加
    public function channel_add()
    {
        if ($this->request->isPost()) {
            $param = input('post.');

            $validate = new \app\admin\validate\Channel();
            $result = $validate->check($param);

            if(!$result){
                $this->error($validate->getError());
            }

            if($param['isedit'] == 0){
                $param['create_time'] = time();
            }
            $param['update_time'] =time();
            $param['uid'] = session('admin_auth.admin_id');
            if($param['isedit'] == 1){
                $book = \app\common\model\Channel::find($param['id']);
            }else{
                $book = new \app\common\model\Channel();
            }

            $msg = $book->allowfield([])->save($param);
            if($msg){
                $this->success('编辑成功');
            }else{
                $this->error('编辑失败');
            }
        }
        $aid = input('aid');
        $agency = \app\common\model\Agency::getAgency();
        $isedit = input('isedit');
        $aname = Db::name('agency')->where('id',$aid)->value('name');
        $map =['isedit'=> $isedit,'agency'=>$agency,'aid'=>$aid,'aname'=>$aname];

        if($isedit == 1){
            $data = Db::name('channel')->where('id',input('id'))->find();
            $map['data'] = $data;
        }

        return $this->fetch('channel_edit',$map);
    }

    //分类删除
    public function channel_del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $uid = Db::name('channel')->where('id','in',$param['id'])->value('uid');
            if(session('admin_auth.admin_id') != 1 || $uid != session('admin_auth.admin_id')) $this->error('无权进行此操作');

            Db::name('channel')->where('id','in',$param['id'])->delete();
            insert_admin_log('删除了保险公司');
            $this->success('删除成功');
        }
    }
}